//
//  ComposeViewController.swift
//  01sinablog
//
//  Created by ZhangZiang on 15/12/23.
//  Copyright © 2015年 ZhangZiang. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    //自定义表情键盘
    private lazy var emoticonKeyView : EmoticonKeyboardView = EmoticonKeyboardView { (em) -> () in
        self.textView.insertEmoticon(em)
    }
    
    // MARK : toolBar的点击事件
    //选择图片
    @objc private func selectPicture() {
        textView.resignFirstResponder()
        
        pictureSelectVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(ScreenH/3 * 2)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    //选择表情
    @objc private func selectEmoticonKeyboard() {
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ? emoticonKeyView : nil
        
        textView.becomeFirstResponder()
        print(__FUNCTION__)
    }
    
    //发微博的网络请求
    @objc private func composeWB() {
        
        var urlString = "2/statuses/update.json"
        
        guard let token = UserAccountViewModel().userAccount?.access_token else {
            SVProgressHUD.showInfoWithStatus("请重新登录")
            return
        }
        //status 是发的内容
        let parameters = ["access_token" : token, "status" : textView.text!]
        
        if pictureSelectVC.imageList.count > 0 {
            //发布带图片的微博
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let imageData = UIImagePNGRepresentation(pictureSelectVC.imageList.first!)
            
            NetworkTool.sharedNetworkTool.uploadImage(parameters, imageData: imageData!, urlString: urlString, finish: { (dict, error) -> () in
                self.finishedUpdate(dict, error: error)
            })
            
        } else {
        //发布文本微博
        NetworkTool.sharedNetworkTool.requestJSONDict(.POST, parameters: parameters, urlString: urlString) { (dict, error) -> () in
            
            self.finishedUpdate(dict, error: error)
        }
        }
    }
    
    private func finishedUpdate(dict: [String : AnyObject]?, error: NSError?) {
        if error != nil {
            SVProgressHUD.showErrorWithStatus("发布失败", maskType: .Gradient)
            return
        }
        
        SVProgressHUD.showSuccessWithStatus("发布成功", maskType: .Gradient)
        
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        
        setupUI()
        
        setToolbar()
        
        setupPictureSelectUI()
        
        //注册通知监听键盘
        registerNotification()
    }
   

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    private func setupNav() {
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "composeWB")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        
        navigationItem.titleView = titleView
        
        let titleLabel = UILabel(title: "发微博", color: UIColor.blackColor(), fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel().userAccount!.name ?? "", color: UIColor.lightGrayColor(), fontSize: 12)
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleLabel.snp_centerX)
            make.top.equalTo(titleLabel.snp_bottom)
        }
    }

    private func setupUI() {
        view.addSubview(textView)
        textView.addSubview(placeHolderView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(view)
            make.height.equalTo(view.bounds.height/3)
        }
        
        placeHolderView.snp_makeConstraints { (make) -> Void in
            make.top.left.equalTo(textView).offset(5)
        }
    }
    
    private func setToolbar() {
        var items = [UIBarButtonItem]()
        
        //向数组中添加元素
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticonKeyboard"],
            ["imageName": "compose_add_background"]]
        
        for item in itemSettings {
            let btn = UIButton(imageName: item["imageName"], backImageName: nil)
            
            if let action = item["actionName"] {
                btn.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside)
            }
            
            let barBtn = UIBarButtonItem(customView: btn)
            let bounce = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            
            items.append(barBtn)
            //加弹簧
            items.append(bounce)
        }
        //移除最后的弹簧
        items.removeLast()
        
        toolBar.items = items
        
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
        }
    }
    //把选择图片的view加到控制器里
    private func setupPictureSelectUI() {
        //先加子控制器
        addChildViewController(pictureSelectVC)
        
        view.addSubview(pictureSelectVC.view)
        
        pictureSelectVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(0)
        }
        
        view.bringSubviewToFront(toolBar)
    }
    
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @objc private func keyboardWillChange(n : NSNotification) {
//        print(n)
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //结构体在字典中用NSValue保存
        let endRect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let offY = endRect.origin.y - ScreenH
        //更新toolBar的约束,相对原来的位置改变了offY
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offY)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
 
    
    //MARK : 懒加载控件
    private lazy var textView : EmoticonTextView = {
        
        let tv = EmoticonTextView()
        
        tv.font = UIFont.systemFontOfSize(18)
        tv.backgroundColor = UIColor.randomColor()
        tv.delegate = self
        //让textView可以上下弹簧效果
        tv.alwaysBounceVertical = true
        //当滑动textView时候让键盘隐藏
        tv.keyboardDismissMode = .OnDrag
        
        return tv
        
    }()
    
    private lazy var placeHolderView = UILabel(title: "请输入要发送的内容", color: UIColor.lightGrayColor(), fontSize: 18, margin: 5)
    
    private lazy var toolBar = UIToolbar()
    
    private lazy var pictureSelectVC = PictureSelectViewController()
}

extension ComposeViewController : UITextViewDelegate {
    //当textView内容改变时候调用下面的方法
    func textViewDidChange(textView: UITextView) {
//        print(__FUNCTION__)
        placeHolderView.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
